class Api::V1::AddressesController < Api::V1::BaseController

  def index
    @addresses = @current_user.addresses.page(params[:page]).per(params[:per])
  end

  def show
    @address = Address.find params[:id]
  end

  def create
    @address = Address.new address_params
    @address.user_id = @current_user.id
    if @address.save
      update_default
    else
      render json: { result: false, message: render_errors(@address.errors.messages) }, status: :ok
    end
  end

  def update
    @address = Address.find params[:id]
    if @address.update address_params
      update_default
      render json: { result: true, message: "更新成功." }, status: :ok
    else
      render json: { result: false, message: render_errors(@address.errors.messages) }, status: :ok
    end
  end

  def destroy
    @address = Address.find params[:id]
    if @address.destroy
      render json: { result: true, message: '删除成功.' }, status: :ok
    else
      render json: { result: false, message: '删除失败.' }, status: :ok
    end
  end

  private

  def update_default
    if @address.is_default
      @current_user.addresses.where.not(id: @address.id).where(is_default: true).update_all(is_default: false)
    end
  end
  

  def address_params
    params.require(:address).permit(:phone, :sendee, :province_id, :city_id, :district_id, :address, :is_default)
  end

end
